import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import Taro from '@tarojs/taro';

// 角色类型常量
export const ROLE_TYPES = {
  STUDENT: 'STUDENT',
  LEADER: 'LEADER'
};

// 创建持久化存储的 store
export const useRoleStore = create(
  persist(
    (set) => ({
      // 默认角色为学生
      userRole: ROLE_TYPES.STUDENT,

      // 切换角色方法
      switchRole: (newRole) => {
        if (Object.values(ROLE_TYPES).includes(newRole)) {
          set({ userRole: newRole });
        }
      },
    }),
    {
      name: 'user-role-storage', // 存储的键名
      storage: createJSONStorage(() => ({
        // 适配 Taro 的存储
        getItem: (name) => {
          const value = Taro.getStorageSync(name);
          return value ? JSON.parse(value) : null;
        },
        setItem: (name, value) => {
          Taro.setStorageSync(name, JSON.stringify(value));
        },
        removeItem: (name) => {
          Taro.removeStorageSync(name);
        },
      })),
    }
  )
);